//
//  PhotoViewController.m
//  SportsSocial
//
//  Created by yull on 14/10/29.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "PhotoViewController.h"
#import "PhotoNet.h"
#import "PlaceNet.h"
#import <UIImageView+WebCache.h>
#import "PhotoCell.h"
#import "PhotoSectionView.h"
#import "YPhotoView.h"
#import "UIScrollView+PullToRefresh.h"
#import "NDRefreshLoadMoreContainView.h"

#define  Photo_Page_Count 10

@interface PhotoViewController () <UICollectionViewDataSource, UICollectionViewDelegate,YPhotoViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UICollectionView *photoCollectionView;

@property (nonatomic, strong) YPhotoView *photoView;

@end

@implementation PhotoViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.photoArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavibar];
    
    [self initCollectionView];
    
    [self initPhotoView];
    
    if (self.currentPage == 0) {
        [self loadPhotoFromServer];
    }
}

- (void)initNavibar
{
    self.navigationItem.title = self.placeId ? @"场馆相册" : @"我的相册";
    [self addCommonBackButton];
    
    if (!self.placeId) {
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        rightButton.frame = CGRectMake(0, 0, 28, 26);
        [rightButton setImage:[UIImage imageNamed:@"title_icon4"] forState:UIControlStateNormal];
        [rightButton setImage:[UIImage imageNamed:@"title_icon4_selection"] forState:UIControlStateHighlighted];
        [rightButton addTarget:self action:@selector(addPhotoClick:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        
        self.navigationItem.rightBarButtonItem = rightItem;
    }
}

- (void)initPhotoView
{
    self.photoView = [[YPhotoView alloc] initWithFrame:self.view.bounds];
    self.photoView.delegate = self;
}

- (void)initCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 8, 10, 8);
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    CGFloat width = (SCREEN_WIDTH - 8 * 2 - 2 * 5) / 3;
    flowLayout.itemSize = CGSizeMake(width, width);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.headerReferenceSize = CGSizeMake(self.view.width, 44);
    
    self.photoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - Navibar_Height) collectionViewLayout:flowLayout];
    self.photoCollectionView.dataSource = self;
    self.photoCollectionView.delegate = self;
    self.photoCollectionView.backgroundColor = [UIColor clearColor];
    [self.photoCollectionView registerClass:[PhotoCell class] forCellWithReuseIdentifier:@"PhotoCell"];
    [self.photoCollectionView registerClass:[PhotoSectionView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PhotoSection"];
    [self.view addSubview:self.photoCollectionView];
    
    if (self.currentPage == self.totalPage) {
        ((NDRefreshLoadMoreContentView *)(self.photoCollectionView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
    } else {
        ((NDRefreshLoadMoreContentView *)(self.photoCollectionView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
    }
    
    @weakify(self);
    [self.photoCollectionView nd_addPullToRefreshWithActionHandler:^(id sender) {
        @strongify(self);
        self.currentPage = 0;
        [self loadPhotoFromServer];
    } loadMoreWithActionHandler:^(id sender) {
        @strongify(self);
        [self loadPhotoFromServer];
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.photoArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSDictionary *dict = [self.photoArray objectAtIndex:section];
    NSArray *photos = [dict.allValues firstObject];
    return photos.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoCell *photoCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCell" forIndexPath:indexPath];
    
    NSDictionary *dict = [self.photoArray objectAtIndex:indexPath.section];
    NSArray *photos = [dict.allValues firstObject];
    NSString *url = [photos objectAtIndex:indexPath.row];
    [photoCell drawCellWithUrl:url];
    return photoCell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    PhotoSectionView *sectionView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PhotoSection" forIndexPath:indexPath];
    NSDictionary *dict = [self.photoArray objectAtIndex:indexPath.section];
    NSString *timeStr = dict.allKeys.firstObject;
    NSArray *photos = [dict.allValues firstObject];
    [sectionView drawSectionViewWithCount:photos.count Time:timeStr];
    return sectionView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *allPhotos = [NSMutableArray array];
    for (NSDictionary *dictArray in self.photoArray) {
        [allPhotos addObjectsFromArray:[dictArray allValues].firstObject];
    }
    
    NSMutableArray *bigPhotoArray = [NSMutableArray array];
    
    for (NSString *photoUrl in allPhotos) {
        YPhoto *photo = [[YPhoto alloc] init];
        photo.thumbUrl = photoUrl;
        photo.imageUrl = photoUrl;
        
        for (PhotoCell *cell in self.photoCollectionView.visibleCells) {
            if ([photoUrl isEqualToString:cell.imageUrl]) {
                CGRect rect = [self.navigationController.view convertRect:cell.imageView.frame fromView:cell.contentView];
                photo.imageRect = rect;
            }
        }
        [bigPhotoArray addObject:photo];
    }
    self.photoView.photoArray = bigPhotoArray;
    
    PhotoCell *cell = (PhotoCell *)[collectionView cellForItemAtIndexPath:indexPath];
    self.photoView.showIndex = [allPhotos indexOfObject:cell.imageUrl];
    
    [self.navigationController.view addSubview:self.photoView];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [self.photoView showPhotoViewWithImage:cell.imageView.image];
}

- (void)loadPhotoFromServer
{
    if (self.placeId) {
        [self getPlacePhoto];
    } else {
        [self getMyPhoto];
    }
}

- (void)getMyPhoto
{
    [PhotoNet photoPaginateWithUserId:[CurrentUser shareInstance].userId PageNumber:self.currentPage + 1 pageSize:Photo_Page_Count successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dataDictionary = [responseObject objectForKey:@"data"];
            
            if (self.currentPage == 0) {
                [self.photoArray removeAllObjects];
            }
            
            self.totalPage = [[dataDictionary objectForKey:@"totalPage"] integerValue];
            self.currentPage = [[dataDictionary objectForKey:@"pageNumber"] integerValue];
            
            NSArray *listArray = [dataDictionary objectForKey:@"list"];
            
            [self parsePhotoArray:listArray];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.currentPage == self.totalPage) {
                    ((NDRefreshLoadMoreContentView *)(self.photoCollectionView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                } else {
                    ((NDRefreshLoadMoreContentView *)(self.photoCollectionView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                }
                [self.photoCollectionView reloadData];
                [self endLoad];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
                [self endLoad];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
            [self endLoad];
        });
    }];
}

- (void)getPlacePhoto
{
    [PlaceNet getPlacePhotoWithPlaceId:self.placeId pageNumber:self.currentPage + 1 pageSize:Photo_Page_Count successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dataDictionary = [responseObject objectForKey:@"data"];
            
            if (self.currentPage == 0) {
                [self.photoArray removeAllObjects];
            }
            
            self.totalPage = [[dataDictionary objectForKey:@"totalPage"] integerValue];
            self.currentPage = [[dataDictionary objectForKey:@"pageNumber"] integerValue];
            
            NSArray *listArray = [dataDictionary objectForKey:@"list"];
            
            [self parsePhotoArray:listArray];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.currentPage == self.totalPage) {
                    ((NDRefreshLoadMoreContentView *)(self.photoCollectionView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                } else {
                    ((NDRefreshLoadMoreContentView *)(self.photoCollectionView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                }
                [self.photoCollectionView reloadData];
                [self endLoad];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
                [self endLoad];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
            [self endLoad];
        });
    }];
}

- (void)parsePhotoArray:(NSArray *)listArray
{
    NSString *lastTimeGroupStr = nil;
    NSDictionary *lastPhotoGroupDic = nil;
    if (self.photoArray.count) {
        lastPhotoGroupDic = self.photoArray.lastObject;
        lastTimeGroupStr = [[lastPhotoGroupDic allKeys] firstObject];
    }
    
    for (NSDictionary *photoDic in listArray) {
        NSString *timeStr = [[photoDic objectForKey:@"upload_date"] substringToIndex:10];
        
        if ([timeStr isEqualToString:lastTimeGroupStr] && timeStr.length) {
            
            NSMutableArray *photoArray = [lastPhotoGroupDic objectForKey:lastTimeGroupStr];
            [photoArray addObject:[photoDic objectForKey:@"file_url"]];
            
        } else {
            
            NSMutableArray *photoArray = [NSMutableArray arrayWithObject:[photoDic objectForKey:@"file_url"]];
            NSDictionary *photoGroupDic = [NSDictionary dictionaryWithObject:photoArray forKey:timeStr];
            [self.photoArray addObject:photoGroupDic];
            
            lastTimeGroupStr = timeStr;
            lastPhotoGroupDic = photoGroupDic;
            
        }
    }
}

- (void)endLoad
{
    [self.photoCollectionView nd_endLoadMore];
    [self.photoCollectionView nd_endRefreshing];
}

#pragma mark - YPhotoDelegate
- (void)photoViewHide
{
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    [self.photoView removeFromSuperview];
}

#pragma mark - Action
- (void)addPhotoClick:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
        if (buttonIndex == 0) {
            [self pickPhoto];
        }else if (buttonIndex == 1) {
            [self takePhoto];
        }
}

#pragma mark - 图片
- (void)takePhoto
{
    BOOL rearCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];//前
    BOOL frontCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    if (!rearCameraAvailable && !frontCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此设备相机不可用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeCamera;//调用相册
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)pickPhoto
{
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//调用相机
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self.navigationController presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //要上传的图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [self uploadImage:image];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImage:(UIImage *)image
{
    [self showHUD];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.3f);
    [PhotoNet uploadPhotoData:imageData successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hideHUD];
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            
            NSDictionary *dataDic = [[responseObject objectForKey:@"data"] objectAtIndex:0];
            
            NSString *timeStr = [[dataDic objectForKey:@"upload_date"] substringToIndex:10];
            if (self.photoArray.count) {
                NSDictionary *latestDic = self.photoArray.firstObject;
                NSString *latestTimeStr = [[latestDic allKeys] firstObject];
                if ([latestTimeStr isEqualToString:timeStr]) {
                    NSMutableArray *latestPhotoArray = [latestDic objectForKey:latestTimeStr];
                    [latestPhotoArray insertObject:[dataDic objectForKey:@"file_url"] atIndex:0];
                } else {
                    NSMutableArray *photoArray = [NSMutableArray arrayWithObject:[dataDic objectForKey:@"file_url"]];
                    NSDictionary *photoGroupDic = [NSDictionary dictionaryWithObject:photoArray forKey:timeStr];
                    [self.photoArray insertObject:photoGroupDic atIndex:0];
                }
            } else {
                NSMutableArray *photoArray = [NSMutableArray arrayWithObject:[dataDic objectForKey:@"file_url"]];
                NSDictionary *photoGroupDic = [NSDictionary dictionaryWithObject:photoArray forKey:timeStr];
                [self.photoArray addObject:photoGroupDic];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"上传成功！" time:2];
                
                [self.photoCollectionView reloadData];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHUD];
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
